import { DataTypes, Model } from 'sequelize';
import sequelize from '../db';
import type Tenant from './Tenant.model';
import type Department from './Department.model';
import type User from './User.model';

/**
 * 公司模型
 */
class Company extends Model {
  public id!: string;
  public tenantId!: string;
  public name!: string;
  public code?: string;
  public legalName?: string;
  public taxId?: string;
  public contactPerson?: string;
  public contactPhone?: string;
  public contactEmail?: string;
  public address?: string;
  public description?: string;
  public status!: 'active' | 'inactive' | 'suspended';
  public sortOrder!: number;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
  public deletedAt?: Date;

  // 关联属性
  public tenant?: Tenant;
  public departments?: Department[];
  public users?: User[];

  /**
   * 是否活跃
   */
  isActive(): boolean {
    return this.status === 'active';
  }
}

Company.init(
  {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    tenantId: {
      type: DataTypes.UUID,
      allowNull: false,
      field: 'tenant_id',
    },
    name: {
      type: DataTypes.STRING(255),
      allowNull: false,
    },
    code: {
      type: DataTypes.STRING(50),
      allowNull: true,
    },
    legalName: {
      type: DataTypes.STRING(255),
      allowNull: true,
      field: 'legal_name',
    },
    taxId: {
      type: DataTypes.STRING(100),
      allowNull: true,
      field: 'tax_id',
    },
    contactPerson: {
      type: DataTypes.STRING(100),
      allowNull: true,
      field: 'contact_person',
    },
    contactPhone: {
      type: DataTypes.STRING(50),
      allowNull: true,
      field: 'contact_phone',
    },
    contactEmail: {
      type: DataTypes.STRING(255),
      allowNull: true,
      field: 'contact_email',
    },
    address: {
      type: DataTypes.TEXT,
      allowNull: true,
    },
    description: {
      type: DataTypes.TEXT,
      allowNull: true,
    },
    status: {
      type: DataTypes.ENUM('active', 'inactive', 'suspended'),
      allowNull: false,
      defaultValue: 'active',
    },
    sortOrder: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      field: 'sort_order',
    },
  },
  {
    sequelize,
    tableName: 'companies',
    underscored: true,
    paranoid: true,
    timestamps: true,
  },
);

export default Company;

